<?php
namespace utils;
use app\admin\model\BaseSetting;
use app\common\library\wechat\Abonus;
use org\RabbitMQ;
use org\Redis;

/**
 *  选出参与分红类
 * Class Dividends
 * @package utils
 */
class Dividends
{

    protected $setting;
    protected $orderInfo;
    /**
     *
     * Dividends constructor.
    // * @param $wxappId  int 小程序商户id
     * @param $setting  string 小程序商户设置信息
     * @param $order  string 订单信息
     */
    public function __construct($setting,$order) {
        $this->setting=$setting;
        $this->orderInfo=$order;
    }

    /**
     * 回退用户订单
     * @param $nowTime int 订单时间
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserBackAbonus($nowTime){

//        $totalMoney=$this->orderInfo['pay_price'];//把金额单位转换成分
//        $systemMoney=$totalMoney*0.01;//系统分的的金额
//        if(!$this->setting
//                || $this->setting['start_time']>$nowTime
//                || $this->setting['end_time']<$nowTime
//                || $this->orderInfo['pay_price']!==$this->orderInfo['total_price']
//                || $this->orderInfo['is_fictitious'] ==2
//            ) {
//
//            $trade = getGuidV4(0);//分账单号
//            $periods_num = 0;
//            //写入分红系统平台得信息
//            $this->setSystenAccounts($trade, $totalMoney, $periods_num);
//            if (intval($systemMoney * 100) >= 8) {
//                //写入服务商分红信息
//                $this->setOperateCenterAccounts($systemMoney, $trade, $periods_num);
//            }
//
//            //写入分红商家得信息
//            $this->setStoreAccounts($trade, $totalMoney, $periods_num);
//            $Abonus = new Abonus($this->orderInfo['wxapp_id']);
//
//            $reault = $Abonus->profitSharings($this->orderInfo);
//
//            if($reault['return_code']=='SUCCESS' && $reault['result_code']=='FAIL' && $reault['err_code'] == 'ORDER_NOT_READY'){
//                $this->profitSharingQuery($order, $Abonus);
//            }
//
//        }
        $rem=new RabbitMQ();
        $data=['orderId'=>$this->orderInfo['order_id'],'time'=>$nowTime];
        file_put_contents("notify4.log",   '参数'.json_encode($data).  "\n", FILE_APPEND);
        $rem->send($data,'userListData','userListDataLog','userListDataLog');


    }





    /**
     *  将系统分红写入数据表
     * @param $trade string 分红期号
     * @param $totalMoney int 分的金额
     */
    private function setSystenAccounts($trade,$totalMoney,$periods_num){

        //获取系统服务商信息
        $systemConfig=BaseSetting::getItem('wechat');
        $system['account']            =$systemConfig['mch_id'];//服务商商户id
        $system['trade']              =$trade;
        $system['order_no']           =$this->orderInfo['order_no'];//订单号
        $system['wxapp_id']           =$this->orderInfo['wxapp_id'];//微信小程序内部编号
        $system['amount']             =$totalMoney*0.01;//分红金额(单位/分)
        if(bcmul($totalMoney,0.01)>=1){
            $system['abonus']             =bcmul(bcmul($totalMoney,0.01),0.2);//分账可得金额(单位/分)
        }else{
            $system['abonus']             =bcmul($totalMoney,0.01,2);//分账可得金额(单位/分)
        }
        $system['description']        ='分账给系统服务商';
        $system['proportion']         =1;//分账比例（百分比）
        $system['payment']            =$totalMoney;//实际支付总金额(单位/分)
        $system['transaction_id']     =$this->orderInfo['transaction_id'];//微信内部订单
        $system['status']             =0;//结算状态 0待分账 1已分账 2分账失败
        $system['create_time']        =time();//写入时间
        $system['periods_num']        =$periods_num;//期号

        db('divide_system')->insert($system);
    }

    /**
     * @param $money int 服务商分红奖金
     * @param $trade  string   分红订单号
     * @param $periods_num  string   分红期号
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setOperateCenterAccounts($money,$trade,$periods_num){
        //获取服务商的id
        $agentId=db('wxapp')->where(['wxapp_id'=>$this->orderInfo['wxapp_id']])->value('agent_id');
        if ($agentId!==0){
            $agentList=db('agent')->where(['is_recycle'=>0,'status'=>1,'is_delete'=>0])->order('agent_id desc')->select();//合伙人层级
            if ($agentList->isEmpty()){
                $tree =Services::instance();
                $tree->init($agentList, 'recommend_id');
                $agentData=$tree->getParents($agentId,true);
                $agentCount=count($agentData);
                // $agentIds=implode(',',$agentData);
                //  $agentDividendsData=collection(db('agent_user')->where('agent_id','in',$agentIds)->where(['is_delete'=>0,'type'=>0,'is_super'=>1])->order('agent_id desc')->select())->toArray();//合伙人层级
                $agentDividendsDataArray=[];
                if($agentCount==1){
                    $agentDividendsDataArray['name']          = $agentData[0]['company_name'];
                    $agentDividendsDataArray['type']          = 1;
                    $agentDividendsDataArray['agent_id']      = $agentData[0]['agent_id'];
                    $agentDividendsDataArray['proportion']    = $agentData[0]['service_charge'];
                    $agentDividendsDataArray['amount']        = bcmul(($agentData[0]['service_charge']/100),$money,2);
                    $agentDividendsDataArray['description']   ='分账给品牌商';
                    $agentDividendsDataArray['trade']         = $trade;//分账单号，小程序号+期号+时间
                    $agentDividendsDataArray['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray['order_no']      = $this->orderInfo['order_no'];//订单号
                    $agentDividendsDataArray['payment']       = $this->orderInfo['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray['transaction_id']= $this->orderInfo['transaction_id'];
                    $agentDividendsDataArray['wxapp_id']      = $this->orderInfo['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray['periods_num']   = $periods_num;//写入时间（支付时间）
                    db('divide_service')->insert($agentDividendsDataArray);
                }elseif ($agentCount==2){
                    $agentDividendsDataArray[0]['name']          = $agentData[0]['company_name'];
                    $agentDividendsDataArray[0]['type']          = 1;
                    $agentDividendsDataArray[0]['agent_id']      = $agentData[0]['agent_id'];
                    $agentDividendsDataArray[0]['proportion']    = bcsub($agentData[0]['service_charge'],$agentData[1]['service_charge']);
                    $agentDividendsDataArray[0]['amount']        = bcmul(($agentDividendsDataArray[0]['proportion']/100),bcmul($money,0.01,2),2);
                    $agentDividendsDataArray[0]['description']   ='分账给品牌商';
                    $agentDividendsDataArray[0]['trade']         = $trade;//分账单号，小程序号+期号+时间
                    $agentDividendsDataArray[0]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray[0]['order_no']      = $this->orderInfo['order_no'];//订单号
                    $agentDividendsDataArray[0]['payment']       = $this->orderInfo['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray[0]['transaction_id']= $this->orderInfo['transaction_id'];
                    $agentDividendsDataArray[0]['wxapp_id']      = $this->orderInfo['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[0]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[0]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[0]['periods_num']   = $periods_num;//写入时间（支付时间）
                    if($agentData[1]['type']==1){
                        //分账给运营商
                        $agentDividendsDataArray[1]['name']          = $agentData[1]['company_name'];
                        $agentDividendsDataArray[1]['type']          = 2;
                        $agentDividendsDataArray[1]['agent_id']      =$agentData[1]['agent_id'];
                        $agentDividendsDataArray[1]['proportion']    =$agentData[1]['service_charge'];
                        $agentDividendsDataArray[1]['amount']        =bcmul(($agentData[1]['service_charge']/100),bcmul($money,0.01,2),2);
                        $agentDividendsDataArray[1]['description']   = '分账给运营商';
                        $agentDividendsDataArray[1]['trade']         = $trade;//分账单号，小程序号+期号+时间
                        $agentDividendsDataArray[1]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                        $agentDividendsDataArray[1]['order_no']      = $this->orderInfo['order_no'];//订单号
                        $agentDividendsDataArray[1]['payment']       = $this->orderInfo['pay_price'];//订单实际支付金额
                        $agentDividendsDataArray[1]['transaction_id']= $this->orderInfo['transaction_id'];
                        $agentDividendsDataArray[1]['wxapp_id']      = $this->orderInfo['wxapp_id'];//内部微信小程序编号
                        $agentDividendsDataArray[1]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                        $agentDividendsDataArray[1]['create_time']   = time();//写入时间（支付时间）
                        $agentDividendsDataArray[1]['periods_num']   = $periods_num;//写入时间（支付时间）
                    }elseif ($agentData[1]['type']==2){
                        //分账给合伙人
                        $agentDividendsDataArray[1]['name']          = $agentData[1]['real_name'];
                        $agentDividendsDataArray[1]['type']          =3;
                        $agentDividendsDataArray[1]['agent_id']      =$agentData[1]['agent_id'];
                        $agentDividendsDataArray[1]['proportion']    =$agentData[1]['service_charge'];
                        $agentDividendsDataArray[1]['amount']        =bcmul(($agentData[1]['service_charge']/100),bcmul($money,0.01,2),2);
                        $agentDividendsDataArray[1]['description']   = '分账给合伙人';
                        $agentDividendsDataArray[1]['trade']         = $trade;//分账单号，小程序号+期号+时间
                        $agentDividendsDataArray[1]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                        $agentDividendsDataArray[1]['order_no']      = $this->orderInfo['order_no'];//订单号
                        $agentDividendsDataArray[1]['payment']       = $this->orderInfo['pay_price'];//订单实际支付金额
                        $agentDividendsDataArray[1]['transaction_id']= $this->orderInfo['transaction_id'];
                        $agentDividendsDataArray[1]['wxapp_id']      = $this->orderInfo['wxapp_id'];//内部微信小程序编号
                        $agentDividendsDataArray[1]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                        $agentDividendsDataArray[1]['create_time']   = time();//写入时间（支付时间）
                        $agentDividendsDataArray[1]['periods_num']   = $periods_num;//写入时间（支付时间）
                    }
                    db('divide_service')->insertAll($agentDividendsDataArray);

                }elseif($agentCount==3){
                    $agentDividendsDataArray[0]['name']          = $agentData[0]['company_name'];
                    $agentDividendsDataArray[0]['type']          = 1;
                    $agentDividendsDataArray[0]['agent_id']      = $agentData[0]['agent_id'];
                    $agentDividendsDataArray[0]['proportion']    = bcsub($agentData[0]['service_charge'],$agentData[1]['service_charge']);
                    $agentDividendsDataArray[0]['amount']        = bcmul(($agentDividendsDataArray[0]['proportion']/100),bcmul($money,0.01,2),2);
                    $agentDividendsDataArray[0]['description']   = '分账给品牌商';
                    $agentDividendsDataArray[0]['trade']         = $trade;//分账单号，小程序号+期号+时间
                    $agentDividendsDataArray[0]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray[0]['order_no']      = $this->orderInfo['order_no'];//订单号
                    $agentDividendsDataArray[0]['payment']       = $this->orderInfo['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray[0]['transaction_id']= $this->orderInfo['transaction_id'];
                    $agentDividendsDataArray[0]['wxapp_id']      = $this->orderInfo['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[0]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[0]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[0]['periods_num']   = $periods_num;//写入时间（支付时间）

                    $agentDividendsDataArray[1]['name']          = $agentData[1]['company_name'];
                    $agentDividendsDataArray[1]['type']          = 2;
                    $agentDividendsDataArray[1]['agent_id']      = $agentData[1]['agent_id'];
                    $agentDividendsDataArray[1]['proportion']    = bcsub($agentData[1]['service_charge'],$agentData[2]['service_charge']);
                    $agentDividendsDataArray[1]['amount']        = bcmul(($agentDividendsDataArray[1]['proportion']/100),bcmul($money,0.01,2),2);
                    $agentDividendsDataArray[1]['description']   = '分账给运营商';
                    $agentDividendsDataArray[1]['trade']         = $trade;//分账单号，小程序号+期号+时间
                    $agentDividendsDataArray[1]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray[1]['order_no']      = $this->orderInfo['order_no'];//订单号
                    $agentDividendsDataArray[1]['payment']       = $this->orderInfo['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray[1]['transaction_id']= $this->orderInfo['transaction_id'];
                    $agentDividendsDataArray[1]['wxapp_id']      = $this->orderInfo['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[1]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[1]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[1]['periods_num']   = $periods_num;//写入时间（支付时间）


                    $agentDividendsDataArray[2]['name']          = $agentData[2]['real_name'];
                    $agentDividendsDataArray[2]['type']          = 3;
                    $agentDividendsDataArray[2]['agent_id']      = $agentData[2]['agent_id'];
                    $agentDividendsDataArray[2]['proportion']    = $agentData[2]['service_charge'];
                    $agentDividendsDataArray[2]['amount']        = bcmul(($agentData[2]['service_charge']/100),bcmul($money,0.01,2),2);
                    $agentDividendsDataArray[2]['description']   ='分账给合伙人';
                    $agentDividendsDataArray[2]['trade']         = $trade;//分账单号，小程序号+期号+时间
                    $agentDividendsDataArray[2]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray[2]['order_no']      = $this->orderInfo['order_no'];//订单号
                    $agentDividendsDataArray[2]['payment']       = $this->orderInfo['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray[2]['transaction_id']= $this->orderInfo['transaction_id'];
                    $agentDividendsDataArray[2]['wxapp_id']      = $this->orderInfo['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[2]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[2]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[2]['periods_num']   = $periods_num;//写入时间（支付时间）
                    db('divide_service')->insertAll($agentDividendsDataArray);
                }

            }
        }


    }

    /**
     *   将商户的分红金额入库
     * @param $trade string 分红期号
     * @param $totalMoney int 总金额
     * @param $periods_num int 分红期号
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setStoreAccounts($trade,$totalMoney,$periods_num){

        $storeConfig=db('wxapp')->where('wxapp_id',$this->orderInfo['wxapp_id'])->find();
        $store['account']            =$storeConfig['mchid'];//服务商商户id
        $store['trade']              =$trade;//分红账号
        $store['order_no']           =$this->orderInfo['order_no'];//订单号
        $store['wxapp_id']           =$this->orderInfo['wxapp_id'];//微信小程序内部编号
        if($periods_num==0){
            $store['amount']         =bcsub($totalMoney,bcmul($totalMoney,0.01));
            $store['proportion']     =bcdiv($store['amount'],$totalMoney,3);//分账比例（百分比）
        }else{
            $store['amount']         =bcmul($totalMoney,($this->setting['realmoney']/100),2);
            $store['proportion']     =$this->setting['realmoney'];//分账比例（百分比）
        }
        $store['agent_id']           = $storeConfig['agent_id'];
        $store['description']        ='分账给商户';
        $store['payment']            =$this->orderInfo['pay_price'];//实际支付总金额(单位/分)
        $store['transaction_id']     =$this->orderInfo['transaction_id'];//微信内部订单
        $store['status']             =0;//结算状态 0待分账 1已分账 2分账失败
        $store['create_time']        =time();//写入时间
        $store['periods_num']        =$periods_num;//期号
        db('divide_store')->insert($store);
    }

    /**
     *  参与分红的商户店员写入数据库
     * @param $trade string  分红期号
     * @param $money int  跟随用户分红的时候的分红金额
     * @param $proportion int 跟随用户分红的时候的分红比例
     * @param $totalMoney int 总支付金额
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setStoreStaffAccounts($trade,$money,$proportion,$totalMoney){

        $staffUserList=db('store_shop_clerk')->where(array('wxapp_id'=>$this->orderInfo['wxapp_id'],'type'=>1,'shop_id'=>$this->orderInfo['extract_shop_id']))->field('clerk_id,open_id,abonus')->select();
        if($staffUserList->isEmpty()){
            return false;
        }else{
            $staffUserDataArray=[];
            foreach ($staffUserList as $key=>$value){
                if($value['pay_type']==0){
                    $staffUserDataArray['amount']        =$money;
                    $staffUserDataArray['proportion']    =$proportion;//分账比例（百分比）
                }else{
                    $staffUserDataArray['amount']        =bcmul(($value['abonus']/100),bcmul($totalMoney,bcsub(1,($this->setting['term']/100))));
                    $staffUserDataArray['proportion']    = $value['abonus'];;//分账比例（百分比）
                }
                    $staffUserDataArray['trade']         =$trade;//代言人id
                    $staffUserDataArray['order_no']      =$this->orderInfo['order_no'];//代言人id
                    $staffUserDataArray['wxapp_id']      =$this->orderInfo['wxapp_id'];//代言人id
                    $staffUserDataArray['clerk_id']      =$value['clerk_id'];//代言人id
                    $staffUserDataArray['account']       =$value['open_id'];
                    $staffUserDataArray['description']   ='分账给商户代言人';
                    $staffUserDataArray['payment']       =$this->orderInfo['pay_price'];
                    $staffUserDataArray['periods_num']   =$this->setting['periods_num'];
                    $staffUserDataArray['transaction_id']=$this->orderInfo['transaction_id'];//代言人id
                    $staffUserDataArray['status']        =0;
                    $staffUserDataArray['create_time']   =time();

            }
            db('divide_store_clerk')->insertAll($staffUserDataArray);
        }
    }


    /***
     *  统计参与分账的代言人
     * @return bool|int|string
     * @throws \think\Exception
     */
    private function getStoreStaffDivideCount(){
        return db('store_shop_clerk')->where(array('wxapp_id'=>$this->orderInfo['wxapp_id'],'type'=>1,'shop_id'=>$this->orderInfo['extract_shop_id']))->count();
    }
    /**
     *  统计参与分红的用户
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getUserAccounts(){
        return db('divide_receives')->where(['wxapp_id'=>$this->orderInfo['wxapp_id'],'type'=>0,'periods_num'=>$this->setting['periods_num']])->count();

    }
    /**
     *  参与分红代言人可以分到的钱
     * @param $totalMoney
     * @return float|int
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getUserMoney($totalMoney){
        $totalUserMoney=$totalMoney*(1-($this->setting['realmoney']/100)-0.01);//用户总的分账金额
        //参与分红的代言人
       // $staff=$this->getStoreStaffDivideCount();
        //如果代言人参与分红
       // if($staff!==false){
       //     $userCount=intval($this->getUserAccounts())+1+$staff;//分账用户总数,加入本次出账方一人和商铺代言人
       // }else{
            $userCount=intval($this->getUserAccounts())+1;//分账用户总数,加入本次的出账方一人
       //     }
        $userMoney=$totalUserMoney/$userCount;//单个用户分账的金额
        return $userMoney;//单位分
    }








}